package com.ylp.sys.auth.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.ylp.common.response.Result;
import com.ylp.sys.auth.entity.LoginDto;
import com.ylp.sys.auth.entity.LoginVo;
import com.ylp.sys.auth.service.AuthService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

@Tag(name = "登录认证接口")
@RestController
@RequestMapping("/auth")
public class AuthController {
    private final AuthService authService;

    public AuthController(AuthService authService) {
        this.authService = authService;
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录")
    public Result<LoginVo> login(@RequestBody LoginDto loginDto) {
        LoginVo loginVo = authService.login(loginDto);
        return Result.success("登录成功", loginVo);
    }


    @Operation(summary = "获取验证码")
    @GetMapping("/getValidate")
    public Result<String> getCode(HttpServletRequest request){
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null) {
            ipAddress = request.getRemoteAddr();
        }

        String code = authService.getCode(ipAddress);
        return Result.success(code);
    }

    @Operation(summary = "验证验证码")
    @PostMapping("/checkValidate")
    public Result<String> checkCode(String code, HttpServletRequest request){
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null) {
            ipAddress = request.getRemoteAddr();
        }
        return authService.checkCode(code, ipAddress);
    }

    @Operation(summary = "退出登录")
    @GetMapping("loginOut")
    public Result<String> loginOut() {
        StpUtil.logout();
        return Result.success("退出登录", null);
    }




}
